/*
 * @Author: your name
 * @Date: 2021-04-29 17:32:23
 * @LastEditTime: 2021-07-21 17:28:31
 * @LastEditors: Please set LastEditors
 * @Description: 上传文件混入
 * @FilePath: \saas\common\mixin\upload.js
 */
import { mapState } from "vuex";
module.exports = {
    data() {
        return {
            /* uploadForm: {
                token: "",
                key: "",
                // persistentOps: "vframe/jpg/offset/0",
            }, //上传参数 */
        };
    },
    onShow() {},
    onLoad(options) {
        // !!this.isLogin ? this.initQiniu() : "";
        this.initQiniu();
    },
    computed: {
        ...mapState("yzhvideo", ["uploadForm"]),
    },
    methods: {
        // 获取七牛上传服务器token
        async initQiniu() {
            const res = await this.$api.common.getQiniuToken({
                team_id: uni.getStorageSync("team_id"),
            });
            if (res.code === 200) {
                // this.uploadForm.token = res.data.token;
                this.$store.commit("yzhvideo/SET_STATE", { uploadForm: {...this.uploadForm, token: res.data.token } });
            } else {
                process.env.SAAS_ENV == "dev" ? this.$u.toast("获取七牛上传服务器token失败!") : "";
                console.log("获取七牛上传服务器token失败 :>> ", res);
            }
        },
        //七牛上传 视频和图片
        upload(url) {
            // this.uploadForm.key = "yzhvideo/wxapp/images" + url.replace(/^http:\/\/tmp|^wxfile:\/\/tmp/, "");
            this.$store.commit("yzhvideo/SET_STATE", {
                uploadForm: {...this.uploadForm, key: "yzhvideo/wxapp/images" + url.replace(/^http:\/\/tmp|^wxfile:\/\/tmp/, "") },
            });
            return new Promise((resolve, reject) => {
                uni.uploadFile({
                    url: "https://up-z2.qiniup.com", //上传地址
                    filePath: url,
                    name: "file",
                    formData: this.uploadForm,
                    success: (res) => {
                        if (res.statusCode == 200) {
                            resolve(JSON.parse(res.data).key);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "none",
                                duration: 1500,
                            });
                            console.log("上传失败 :>> ", res);
                            reject(res);
                        }
                    },
                    fail: (err) => {
                        reject(err);
                    },
                });
            });
        },
    },
};